package com.yanxu.nio.c1;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/12/22-2024
 * @Description: ByteBuffer 和 字符串之间的转换。
 */
public class Test5_ByteBuffer2String {
    public static void main(String[] args) {
        String str="hello";

        //1: 将一个字符串转换成 byteBuffer
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(16);
        byteBuffer1.put(str.getBytes());

        //2：Charset
        ByteBuffer byteBuffer2 = Charset.defaultCharset().encode(str);

        //3：wrap
        ByteBuffer byteBuffer3 = ByteBuffer.wrap(new byte[]{'a', 'b', 'c', 'd'});




        //====================================================分割线====================================================
        //将一个 ByteBuffer 转换为String 字符串
        ByteBuffer byteBuffer4 = ByteBuffer.allocate(16);
        byteBuffer4.put(str.getBytes());
        String s = Charset.defaultCharset().decode(byteBuffer4).toString();
    }
}